/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.yzbdl.lanius.orchestrate.serv.dto.system.VerifyCodeDto;
import org.yzbdl.lanius.orchestrate.serv.utils.VerifyCodeUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * 验证码接口
 *
 * @author chenjunhao@yzbdl.ac.cn
 * @date 2022-04-25 14:17
 */
@Api(tags = "验证码接口")
@RestController
@RequestMapping("/verify")
@Validated
public class VerifyController {

	@ApiOperation(value="获取验证码", notes="")
	@RequestMapping(value = "/{key}", method = RequestMethod.GET)
	public void verifyImg(HttpServletRequest request, HttpServletResponse response, @PathVariable("key") String key){
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200,100);
		try{
			request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
			response.setContentType("image/png");
			response.setHeader("Pragma","No-cache");
			response.setHeader("Cache-Control","no-cache");
			response.setDateHeader("Expire",0);
			VerifyCodeUtil.addCode(key, VerifyCodeDto.builder().lineCaptcha(lineCaptcha).expireDate(LocalDateTime.now().plusMinutes(2)).build());
			lineCaptcha.write(response.getOutputStream());
		}catch (Exception e){
			e.printStackTrace();
		}
	}

}
